package com.leyou.mq;

import com.leyou.constants.MQConstants;
import com.leyou.utils.RegexUtils;
import com.leyou.utils.SmsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Map;

import static com.leyou.constants.MQConstants.*;
/**
 * @author jshstart
 * @creat 2020-12-22 15:48
 */
@Slf4j
@Component
public class MessageListener {
    @Autowired
    private SmsUtil smsUtil;
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name=QueueConstants.SMS_VERIFY_CODE_QUEUE,durable = "true"),
            exchange = @Exchange(name = ExchangeConstants.SMS_EXCHANGE_NAME,type = ExchangeTypes.TOPIC),
            key = RoutingKeyConstants.VERIFY_CODE_KEY
    ))
    public void listenSendCode(Map<String,String> msg){
        //如果map是null，直接返回不处理
        if (CollectionUtils.isEmpty(msg)){
            return;
        }
        String phone = msg.get("phone");
        if (!RegexUtils.isPhone(phone)){
            //如果手机号有误，不处理
            return;
        }
        String code = msg.get("code");
        if (!RegexUtils.isCodeValid(code)){
            //如果验证码有误，不处理
            return;
        }
        try {
            //发送短信
            smsUtil.sendVerifyCode(phone,code);
        } catch (Exception e) {
            //短信发送失败
            log.error("【SMS服务】短信验证码发送失败", e);
        }
    }
    @Bean
    public Jackson2JsonMessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }

}
